package com.ljh.lottery.common.interceptor;

import com.ljh.lottery.common.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author: Themberfue
 * @date: 2025/4/10 23:27
 * @description:
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
    private static final String USER_TOKEN_HEADER_KEY = "user_token";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // TODO 1. 从请求头中获取 token
        String token = request.getHeader(USER_TOKEN_HEADER_KEY);

        // TODO 2. 打印日志
        log.info("从 header 中获取 token：{}", token);
        log.info("获取路径：{}", request.getRequestURL());

        // TODO 3. 解析 token
        if (token == null || JwtUtil.parseJWT(token) == null) {
            log.error("解析 token 失败");
            response.setStatus(401);
            return false;
        }
        log.error("解析 token 成功");
        return true;
    }
}
